package com.boyou.sytzc.utils.common

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.ActivityCompat
import android.telephony.TelephonyManager
import androidx.core.content.edit

/**
 * 设备号管理单例类
 * @param ctx 上下文对象
 */
class DeviceNoManager private constructor(private val ctx: Context) {

    companion object {
        // 设备号
        private const val KEY_DEVICE_NO = "deviceNo"

        // APP是否是第一次运行
        private const val KEY_IS_APP_FIRST_EXEC = "isAppFirstExec"

        @SuppressLint("StaticFieldLeak")
        private var instance: DeviceNoManager? = null

        fun getInstance(ctx: Context): DeviceNoManager {
            if (instance == null) {
                synchronized(DeviceNoManager::class.java) {
                    instance = DeviceNoManager(ctx)
                }
            }
            return instance!!
        }

    }

    private var _sharedPreferences = ctx.getSharedPreferences("device_no_conf.xml", 0)

    // 获取由系统获取的设备号
    private val _sysDeviceNo: Pair<Boolean, String?>
        @SuppressLint("HardwareIds")
        @Suppress("DEPRECATION")
        get() {
            if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED
            ) return Pair(false, null)
            val tm = (ctx.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager)
            val deviceNo = when {
                Build.VERSION.SDK_INT <= Build.VERSION_CODES.O -> tm.deviceId
                else -> null
            }
            val isDeviceNoEnabled = !deviceNo.isNullOrEmpty()
            _sharedPreferences.edit(true) {
                if (isDeviceNoEnabled)
                    putString(KEY_DEVICE_NO, deviceNo)
                putBoolean(KEY_IS_APP_FIRST_EXEC, false)
            }
            return Pair(isDeviceNoEnabled, deviceNo?.trim())
        }

    // 应用是否是第一次执行
    val isAppFirstExec: Boolean
        get() = _sharedPreferences.getBoolean(KEY_IS_APP_FIRST_EXEC, true)

    /** 设备号是否可用 **/
    val isDeviceNoEnabled: Boolean get() = !deviceNo.isNullOrEmpty()

    /** 设备号 **/
    var deviceNo: String?
        set(value) {
            _sharedPreferences.edit(true) {
                putString(KEY_DEVICE_NO, value)
                if (isAppFirstExec) putBoolean(KEY_IS_APP_FIRST_EXEC, false)
            }
        }
        get() = (when {
            isAppFirstExec -> _sysDeviceNo.second
            else -> _sharedPreferences.getString(KEY_DEVICE_NO, "")
        })?.trim()

}